﻿/*
The MIT License (MIT)
Copyright (c) 2013 David Walker

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/// <reference path="jquery-1.10.2.js" />

var SubtractJS = function ($) {
    var isInitialized = false;
    var doBodyInitialize = true;
    var isResizing = false;
    var isSubtractJSPaused = false;
    var beforeResize = function () { };
    var prefix = "sj";
    var fillerSelector;
    var widthElementsSelector;
    var heightElementsSelector;
    var elementsSelector;
    var selectorList;

    var nextParentId = 0;

    function initializePrefix() {
        fillerSelector = "." + prefix + "-fill";
        widthElementsSelector = "." + prefix + "-fill-left,." + prefix + "-fill-right";
        heightElementsSelector = "." + prefix + "-fill-top,." + prefix + "-fill-bottom";
        elementsSelector = fillerSelector + "," + widthElementsSelector + "," + heightElementsSelector;
        selectorList = elementsSelector.replace(/\./g, "").split(",");
    }

    function getEdgeWidth(element, edge) {
        var margin = parseIntWithDefault(element.css("margin-" + edge), 0);
        var border = parseIntWithDefault(element.css("border-" + edge + "-width"), 0);
        var padding = parseIntWithDefault(element.css("padding-" + edge), 0);

        var borderStyle = element.css("border-" + edge + "-style");

        if (borderStyle === "none" || borderStyle === "hidden") {
            border = 0;
        }

        return margin + border + padding;
    }

    function parseIntWithDefault(text, defaultValue) {
        return replaceNaNWithX(parseInt(text, 10), defaultValue);
    }

    function replaceNaNWithX(number, x) {
        if (isNaN(number)) {
            return x;
        } else {
            return number;
        }
    }

    function startsWith(str1, str2) {
        return str1.indexOf(str2) === 0;
    }

    function resizeScreen() {
        if (isResizing || isSubtractJSPaused) {
            $("#" + prefix + "-curtain").hide();
            return;
        }

        isResizing = true;

        resetData();

        beforeResize();

        if (!isSubtractJSPaused) {
            var parents = $("." + prefix + "-parent:visible");

            parents.not(fillerSelector).each(subtractElementFromParentBox);
            parents.filter(fillerSelector).each(subtractElementFromParentBox);
        }

        isResizing = false;
        $("#" + prefix + "-curtain").hide();
    }

    function resetData() {
        $(elementsSelector)
            .filter(":not(." + prefix + "-ignore):visible")
            .addClass(prefix + "-subtract")
            .css({
                "position": "absolute",
                "display": "block"
            });

        $("." + prefix + "-subtract:visible").each(function () {
            var self = $(this);
            var parent = self.offsetParent();

            parent.css("overflow", "hidden");

            parent
                .data(prefix + "-top", 0)
                .data(prefix + "-left", 0)
                .data(prefix + "-width", parent.innerWidth())
                .data(prefix + "-height", parent.innerHeight());

            parent.css("overflow", "");

            var myParentId = parent.data(prefix + "-id");
            if (myParentId === undefined) {
                if (!parent.hasClass(prefix + "-subtract")) {
                    parent.addClass(prefix + "-parent");
                }
                parent.data(prefix + "-id", nextParentId);

                myParentId = nextParentId;

                nextParentId++;
            }

            self.addClass(prefix + "-parent-" + myParentId);
        });
    }

    function subtractElementFromParentBox() {
        /*jshint validthis: true */
        var self = $(this);
        var selectedElements;

        if (self.hasClass(prefix + "-ignore")) {
            return;
        }

        self.css("overflow", "hidden");

        if (!self.hasClass(prefix + "-subtract")) {
            if (!self.hasClass(prefix + "-ignore-children")) {
                var parentClassSelector = "." + prefix + "-parent-" + self.data(prefix + "-id") + ":visible";

                selectedElements = self.find(parentClassSelector);
                selectedElements.not(fillerSelector).each(subtractElementFromParentBox);

                var fillerElements = selectedElements.filter(fillerSelector);
                fillerElements.each(subtractElementFromParentBox);
            }

            self.css("overflow", "");

            return;
        }

        resetElement(self);

        var parent = self.offsetParent();
        parent.css("overflow", "hidden");

        var top = parent.data(prefix + "-top");
        var left = parent.data(prefix + "-left");
        var width = parent.data(prefix + "-width");
        var height = parent.data(prefix + "-height");

        var widthStyle = "fixed";
        var heightStyle = "fixed";
        var verticalAlign = "top";
        var horizontalAlign = "left";
        var adjustHeight = false;
        var adjustWidth = false;
        var adjustBoxModel = self.hasClass(prefix + "-margin-box-model");

        if (self.hasClass(prefix + "-fill")) {
            heightStyle = "fill";
            widthStyle = "fill";
        }

        if (self.hasClass(prefix + "-fill-right")) {
            horizontalAlign = "right";
            heightStyle = "fill";
            adjustWidth = true && adjustBoxModel;
        }

        if (self.hasClass(prefix + "-fill-left")) {
            horizontalAlign = "left";
            heightStyle = "fill";
            adjustWidth = true && adjustBoxModel;
        }

        if (self.hasClass(prefix + "-fill-top")) {
            verticalAlign = "top";
            widthStyle = "fill";
            adjustHeight = true && adjustBoxModel;
        }

        if (self.hasClass(prefix + "-fill-bottom")) {
            verticalAlign = "bottom";
            widthStyle = "fill";
            adjustHeight = true && adjustBoxModel;
        }

        if (widthStyle === "fixed" && heightStyle === "fixed") {
            throw "SubtractJS: No element may have both fixed height and fixed width";
        }

        var newHeight, newWidth;

        if (adjustHeight) {
            newHeight = self.height() - (getEdgeWidth(self, "top") + getEdgeWidth(self, "bottom"));
            self.css({
                "height": newHeight + "px"
            });
        }

        if (adjustWidth) {
            newWidth = self.width() - (getEdgeWidth(self, "left") + getEdgeWidth(self, "right"));
            self.css({
                "width": newWidth + "px"
            });
        }

        var myWidth = self.outerWidth(true);
        var myHeight = self.outerHeight(true);

        if (widthStyle === "fixed") {
            if (horizontalAlign === "left") {
                self.css({
                    "left": left + "px"
                });

                left += myWidth;
                width -= myWidth;
            } else {
                self.css({
                    "left": (width + left - myWidth) + "px"
                });

                width -= myWidth;
                if (width < 0) {
                    width = 0;
                }
            }
        } else if (widthStyle === "fill") {
            // fill
            newWidth = width - (getEdgeWidth(self, "left") + getEdgeWidth(self, "right"));

            self.css({
                "left": left + "px",
                "width": newWidth + "px"
            });
        }

        if (heightStyle === "fixed") {
            if (verticalAlign === "top") {
                self.css({
                    "top": top + "px"
                });

                top += myHeight;
                height -= myHeight;
            } else {
                self.css({
                    "top": (top + height - myHeight) + "px"
                });

                height -= myHeight;
                if (height < 0) {
                    height = 0;
                }
            }
        } else if (heightStyle === "fill") {
            // fill
            newHeight = height - (getEdgeWidth(self, "top") + getEdgeWidth(self, "bottom"));

            self.css({
                "top": top + "px",
                "height": newHeight + "px"
            });
        }

        parent.data(prefix + "-top", top);
        parent.data(prefix + "-left", left);
        parent.data(prefix + "-width", width);
        parent.data(prefix + "-height", height);

        if (!(self.data(prefix + "-id") === undefined && !self.hasClass(prefix + "-ignore-children"))) {
            self.data(prefix + "-top", 0);
            self.data(prefix + "-left", 0);
            self.data(prefix + "-width", self.innerWidth());
            self.data(prefix + "-height", self.innerHeight());

            var parentClass = "." + prefix + "-parent-" + self.data(prefix + "-id");

            selectedElements = self.find(parentClass);
            selectedElements.not(fillerSelector).each(subtractElementFromParentBox);
            selectedElements.filter(fillerSelector).each(subtractElementFromParentBox);
        }

        parent.css("overflow", "");
        self.css("overflow", "");
    }

    function clearSubtractJS(selector, fullClear) {
        /// <signature>
        ///   <summary>Clear SubtractJS classes and properties from element.</summary>
        ///   <param name="selector" type="String"></param>
        ///   <param name="fullClear" type="Boolean"></param>
        /// </signature>
        var elements = $(selector);

        elements.each(function () {
            var self = $(this);
            clearElement(self, fullClear);
        });
    }

    function clearElement(thisElement, fullClear) {
        if (fullClear) {
            var classAttr = thisElement.attr('class') || "";
            var classes = classAttr.split(/\s+/);

            classes.forEach(function (item) {
                if (startsWith(item, prefix)) {
                    thisElement.removeClass(item);
                }
            });
        }

        thisElement
            .css({
                "width": "",
                "height": "",
                "left": "",
                "top": "",
                "right": "",
                "bottom": "",
                "display": "",
                "position": ""
            });
    }

    // http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
    var debounce = function (func, threshold, execAsap) {
        var timeout;

        return function debounced() {
            var obj = this, args = arguments;
            function delayed() {
                if (!execAsap) {
                    func.apply(obj, args);
                }
                timeout = null;
            }

            if (timeout) {
                clearTimeout(timeout);
            }
            else if (execAsap) {
                func.apply(obj, args);
            }

            timeout = setTimeout(delayed, threshold || 50);
        };
    };

    function initializeScreen() {
        initializePrefix();

        isInitialized = true;

        if (doBodyInitialize) {
            $("html,body").css({
                "height": "100%",
                "width": "100%",
                "margin": "0",
                "padding": "0",
                "border": "0px none"
            });

            $("body").append("<div id=\"" + prefix + "-curtain\" style=\"height: 100%; width: 100%; position: absolute; top: 0; left: 0; margin: 0; padding: 0; border: 0px none; background: red; z-index: 100; display: none;\"></div>");
        }

        resizeScreen();
        $(window).resize(debounce(resizeScreen));
    }

    function resetElement(self) {
        self
            .css({
                width: "",
                height: ""
            });
    }

    if ($) {
        $(initializeScreen);
    }
    else {
        throw "jQuery is not available in SubtractJS";
    }

    return {

        Initialize: function () {
            initializeScreen();
            return this;
        },

        Pause: function () {
            isSubtractJSPaused = true;
            return this;
        },

        Unpause: function () {
            isSubtractJSPaused = false;
            return this;
        },

        IsPaused: function () {
            return isSubtractJSPaused;
        },

        SetBodyNoInit: function () {
            doBodyInitialize = false;
        },

        SetPrefix: function (newPrefix) {
            if (isInitialized) {
                throw "SetPrefix can only be called prior to initialization.";
            }
            prefix = newPrefix;
            return this;
        },

        ClearSubtractJS: function (selector, fullClear) {
            /// <signature>
            ///   <summary>Reset the properties that SubtractJS manipulates</summary>
            ///   <param name="selector" type="string"></param>
            ///   <param name="fullClear" type="Boolean"></param>
            /// </signature>
            clearSubtractJS(selector, fullClear);
            return this;
        },

        BeforeResize: function (beforeResizeFunction) {
            /// <signature>
            ///   <summary>Pass in a function to execute before resizing</summary>
            ///   <param name="beforeResizeFunction" type="Function"></param>
            /// </signature>
            beforeResize = beforeResizeFunction;
            return this;
        },

        UpdateLayout: function () {
            /// <signature>
            ///   <summary>Call the SubtractJS resize event.</summary>
            /// </signature>
            resizeScreen();
            return this;
        }
    };
}(jQuery);



